﻿Public Class oInvoices
    Public Function CreateInvoice(ByVal NightAuditheader As DataRow)
        Dim cn As New Connection
        Dim dtHeader As DataTable = New DataTable
        Dim dtLine As DataTable = New DataTable
        Dim errMessage As String = ""
        Dim ds As DataSet = New DataSet
        Dim DocType As String = "13"
        Dim ret As String = ""
        Dim xm As New oXML
        Dim tableOINV As DataTable = Functions.BuildTable("OINV", "CardCode;CardName;DocDate;DocDueDate")
        Dim tableINV1 As DataTable = Functions.BuildTable("INV1", "ItemCode;Dscription;WhsCode;Quantity;PriceBefDi;OcrCode2;OcrCode3;OcrCode4")

        dtHeader = cn.Integration_RunQuery(String.Format("select * from NightAuditInvHeader where HeaderID = {0}", NightAuditheader("ID")))
        If dtHeader.Rows.Count > 0 And dtLine.Rows.Count > 0 Then
            For Each rowHeader As DataRow In dtHeader.Rows
                dtLine = cn.Integration_RunQuery(String.Format("select * from NightAuditInvDetail where HeaderID = {0}", rowHeader("ID")))
                If dtLine.Rows.Count > 0 Then
                    Try
                        tableOINV.Rows.Add(rowHeader("CardCode"), rowHeader("CardName"), rowHeader("CheckOutDate"), rowHeader("CheckOutDate"))
                        For Each rowLine As DataRow In dtLine.Rows
                            tableINV1.Rows.Add(rowLine("ItemCode"), rowLine("Description"), rowLine("OutLet"), rowLine("Quantity"), rowLine("Price"), rowLine("Division"), rowLine("Department"), rowLine("MarketSegment"))
                        Next

                        ds.Tables.Add(tableOINV.Copy)
                        ds.Tables.Add(tableINV1.Copy)

                        Dim sErrMsg As String
                        sErrMsg = Functions.SystemInitial
                        If sErrMsg <> "" Then
                            Throw New Exception(sErrMsg)
                        End If

                        'Do somethings
                        Dim xmlstr As String = xm.ToXMLStringFromDS(DocType, ds)
                        ret = xm.CreateMarketingDocument("", xmlstr, DocType)

                        If ret <> "" Then
                            Throw New Exception(ret)
                        End If

                        Return ""
                    Catch ex As Exception
                        Return ex.Message
                    End Try
                End If
            Next
            

        End If
        Return errMessage
    End Function
End Class
